package order;

import beans.Car;
import beans.Good;
import cart.Cart;
import order.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class OrderService {
    private OrderDao orderDao = new OrderDao();
    private OrderItemDao orderItemDao = new OrderItemDao();
    private GoodsDao goodsDao = new GoodsDao();
    // 生成订单
    public Order saveOrder(List<Car> cart, String userId){
        // 生成订单号
        String orderId = String.valueOf(System.currentTimeMillis());
        // 订单生成时间
        Timestamp createTime = Timestamp.valueOf(LocalDateTime.now());
        Iterator<Car> it = cart.listIterator();
        BigDecimal sum = null;
        int sumStock=0;
       for (int i=0;i<cart.size();i++){
           sum= BigDecimal.valueOf(cart.get(i).getTotalPrice());
           sumStock= Integer.parseInt(cart.get(i).getQuantity());
           BigDecimal  unitprice= new BigDecimal(cart.get(i).getTotalPrice());
           BigDecimal  unitprice1= new BigDecimal(cart.get(i).getUnitprice());

           cart.get(i).getGoods_id();
           OrderItem orderItem =
                   new OrderItem(null, cart.get(i).getPic(),cart.get(i).getGoods_name(),unitprice1, Integer.parseInt(cart.get(i).getQuantity().trim()),unitprice, orderId);
           orderItemDao.addOrderItem(orderItem);
           // 得到商品信息
           Good goods = goodsDao.singleData(String.valueOf(cart.get(i).getGoods_id()));
           goods.setStock(goods.getStock()-sumStock);

           // 更新到数据库
           goodsDao.updateData(goods);
       }

        
        Order order = new Order(orderId,createTime,sum,0,userId);
        // 保存order表到数据库
        orderDao.addOrder(order);
        // 构建orderItem，并保存到数据库



        // 清空购物车

        for (int i=cart.size()-1;i>=0;i--){
            cart.remove(i);
        }

        return order;
    }

    // 显示所有订单
    public List<Order> showAllOrder(String userId){
        return orderDao.showAllOrder(userId);
    }
}

